package com.kuaishou.locallife.open.api.common.utils;

import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Logger;


/**
 * @author kangbin <kangbin@kuaishou.com>
 * Created on 2020-09-07
 */
public class SortUtils {
    protected static final Logger logger = Logger.getLogger(SortUtils.class.getName());

    private SortUtils() {
    }

    /**
     * 按照key的字典顺序排序后用&连接 key=value
     */
    public static String sortAndJoin(Map<String, String> params) {
        TreeMap<String, String> paramsTreeMap = new TreeMap();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (entry.getValue() == null) {
                continue;
            }

            paramsTreeMap.put(entry.getKey(), entry.getValue());
        }

        String signCalc = "";
        for (Map.Entry<String, String> entry : paramsTreeMap.entrySet()) {
            signCalc = String.format("%s%s=%s&", signCalc, entry.getKey(), entry.getValue(), "&");
        }
        if (signCalc.length() > 0) {
            signCalc = signCalc.substring(0, signCalc.length() - 1);
        }

        return signCalc;
    }
}
